// 引入express模块
var express = require('express');
const compression = require('compression');
var app = express();
const bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(compression({
    // 可选配置项：
    level: 9,          // 压缩级别 1-9（默认 6）
    threshold: '1kb',  // 超过 1KB 才压缩（默认）
    filter: (req, res) => {
        // 可自定义压缩条件
        if (req.headers['x-no-compression']) return false
        return compression.filter(req, res)
    }
}));
app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();
});

// 定义路由
app.get('/', function (req, res) {
    res.send("Hello")
})

app.get('/class_list', function (req, res) {
    res.send([
        {
            name: "文化课班",
            id: 1
        }, {
            name: "外语班",
            id: 2
        }, {
            name: "体育班",
            id: 3
        }
    ])
})

app.get('/student_list', function (req, res) {
    res.send([
        {
            name: "小明",
            id: 1,
            class: 1
        }, {
            name: "小亮",
            id: 2,
            class: 1
        }, {
            name: "小武",
            id: 3,
            class: 1
        }, {
            name: "Jack",
            id: 4,
            class: 2
        }, {
            name: "Lily",
            id: 5,
            class: 2
        }, {
            name: "Jesse",
            id: 6,
            class: 2
        }, {
            name: "苏饼添",
            id: 7,
            class: 3
        }, {
            name: "榴翔",
            id: 8,
            class: 3
        }, {
            name: "笋杨",
            id: 9,
            class: 3
        },
    ])
})

const fs = require("fs")
const path = require('path');
app.get("/large_data_bind", function (req, res) {
    try {
        const JSON_FILE_PATH = path.join(__dirname, 'largedata_bind.json')
        let fileContent = fs.readFileSync(JSON_FILE_PATH, 'utf-8')
        res.json(JSON.parse(fileContent))
    } catch (error) {
        // 错误处理
        console.error('Error:', error);
        res.status(500).json({
            error: 'Failed to load JSON data',
            details: error.message
        });
    }
})
app.get("/large_data", function (req, res) {
    try {
        const JSON_FILE_PATH = path.join(__dirname, 'largedata.json')
        let fileContent = fs.readFileSync(JSON_FILE_PATH, 'utf-8')
        res.json(JSON.parse(fileContent))
    } catch (error) {
        // 错误处理
        console.error('Error:', error);
        res.status(500).json({
            error: 'Failed to load JSON data',
            details: error.message
        });
    }
})

// 启动服务器
app.listen(3000, function () {
    console.log('Server started on port 3000');
});